package cn.softgame.jserver.connector.tcp;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.Set;


public class TCPReactor implements Runnable{

	private static String module = TCPReactor.class.getName();
	private Selector selector;
	private ServerSocketChannel ssc;
	
	public TCPReactor(int port) throws IOException{
		selector = Selector.open();
		ssc = ServerSocketChannel.open();
		InetSocketAddress address = new InetSocketAddress(InetAddress.getLocalHost(), port);
		ssc.socket().bind(address);
		System.out.println("-->Start host:"+ InetAddress.getLocalHost()+" port=" + port);
		ssc.configureBlocking(false);
		SelectionKey sk = ssc.register(selector, SelectionKey.OP_ACCEPT);
		sk.attach(new Acceptor(selector,ssc));
		System.out.println("-->attach(new Acceptor())!");
	}
	
	@Override
	public void run() {
		try {
			while(!Thread.interrupted()){
				int select = selector.select();
				if(select>0){
					Set<SelectionKey> selected = selector.selectedKeys();
					for(Iterator<SelectionKey> iter=selected.iterator();iter.hasNext();){
						dispatch(iter.next());
					}
					selected.clear();
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("reactor stop!"+ module);
		}
	}

	private void dispatch(SelectionKey sk){
		Runnable acceptor = (Runnable) sk.attachment();
		if(acceptor!=null){
			System.out.println("-->dispatch running");
			acceptor.run();
		}
	}
}
